package cn.xiangxiang.service.impl;

import cn.xiangxiang.mapper.order.OrderConfigMapper;
import cn.xiangxiang.pojo.order.Order;
import cn.xiangxiang.pojo.order.OrderConfig;
import cn.xiangxiang.pojo.order.OrderLog;
import cn.xiangxiang.service.order.OrderConfigService;
import cn.xiangxiang.service.order.OrderLogService;
import cn.xiangxiang.service.order.OrderService;
import cn.xiangxiang.service.utils.IdWorker;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service(interfaceClass = OrderConfigService.class)
public class OrderConfigServiceImpl extends ServiceImpl<OrderConfigMapper, OrderConfig> implements OrderConfigService {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderLogService orderLogService;
    @Autowired
    private IdWorker idWorker;


    // 关闭超时订单
    @Transactional
    public void closeTimeoutOrder() {

        OrderConfig config = getOne(null);

        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(config.getOrderTimeout());

        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("pay_status", "0").eq("consign_status", "0").eq("is_delete", "0").le("create_time", localDateTime);

        List<Order> orderList = orderService.list(wrapper);

        ArrayList<OrderLog> orderLogList = new ArrayList<>();

        orderList.forEach((order) -> {
            order.setOrderStatus("4");
            order.setCloseTime(new Date());
            order.setUpdateTime(new Date());


            OrderLog orderLog = new OrderLog();

            orderLog.setId(idWorker.nextId() + "");
            orderLog.setOrderId(order.getId());
            orderLog.setOperater("system");
            orderLog.setOperateTime(order.getUpdateTime());
            orderLog.setOrderStatus(order.getOrderStatus());
            orderLog.setPayStatus(order.getPayStatus());
            orderLog.setConsignStatus(order.getConsignStatus());
            orderLog.setRemarks("无");

            orderLogList.add(orderLog);
        });

        orderService.updateBatchById(orderList);

        // 记录日志
        orderLogService.saveBatch(orderLogList);

    }
}
